package com.xiangming.demo.controller;

import com.xiangming.demo.service.UploadService;
import com.xiangming.demo.utils.Result;
import com.xiangming.demo.entity.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

/**
 * @author wxm
 * @data 2021/11/12
 */
@RestController
public class UploadController {
    Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    UploadService uploadService;

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    /**
     * 文件上传接口
     * @param file 文件
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {

        //设置重命名
        UUID uuid = UUID.randomUUID();
        String uuidString = uuid.toString();

        //判断文件是否为空
        if (file.isEmpty()) {
            return new Result(false, StatusCode.EMPTY, "文件为空");
        }

        //进行文件上传操作
        Boolean uploading = uploadService.uploading(file, uuidString);
        if (uploading) {
            logger.info("-----debug------请求执行成功");
           return new Result(true, StatusCode.OK, "上传成功", uuidString);
        } else {
            logger.info("-----debug------请求执行失败");
          return   new Result(false, StatusCode.ERROR, "上传失败");

        }


    }
}
